package com.gimi.cloud.jimi.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTools {

	/**
	 * 接受数据
	 * 
	 * @param socket
	 * @return
	 * @throws IOException
	 * @throws DataRequestException
	 */
	public static String reciveData(Socket socket) {
		InputStream in = null;
		String returnVal = null;
		try {
			in = socket.getInputStream();
			socket.setSoTimeout(30 * 1000);
			// 获取
			byte[] b = readStream(in);
			SubTool subtool = new SubTool();
			returnVal = subtool.formatString(b);// 通过网络字节顺序的缓冲区中解析字符串

		} catch (IOException e) {
			e.printStackTrace();

		} finally {

			if (in != null) {
				try {
					socket.shutdownInput();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return returnVal;
	}

	/**
	 * 发送数据
	 * 
	 * @param socket
	 * @throws IOException
	 * @throws DataRequestException
	 */
	public static void sendData(Socket socket, String data) {
		
		OutputStream out = null;
		try {
			out = socket.getOutputStream();
			out.write(data.getBytes("utf-8"));
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(out != null){
				try {
					socket.shutdownOutput();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static byte[] readStream(InputStream inStream) throws IOException,SocketTimeoutException {
		int count = 0;
		long start = System.currentTimeMillis();
		while (count == 0) {
			count = inStream.available();
			long end = System.currentTimeMillis();
			if(end - start >=5000){
				return null;
			}
		}
		byte[] b = new byte[count];
		inStream.read(b);
		return b;
	}
}
